<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="学生姓名" prop="studentName">
        <el-input
          v-model="queryParams.studentName"
          placeholder="请输入学生姓名"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="方向" prop="directionId" style="width: 180px">
        <el-select
          v-model="queryParams.directionId"
          placeholder="请选择方向"
          clearable
          @keyup.enter="handleQuery"
        >
          <el-option
            v-for="item in directionOptions"
            :key="item.directionId"
            :label="item.directionName"
            :value="item.directionId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="位置编号" prop="deskId">
        <el-input
          v-model="queryParams.deskId"
          placeholder="请输入位置编号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="开始时间" prop="startTime" style="width: 220px">
        <el-date-picker
          v-model="queryParams.startTime"
          type="datetime"
          placeholder="请选择开始时间"
          value-format="YYYY-MM-DD HH:mm:ss"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="结束时间" prop="endTime" style="width: 220px">
        <el-date-picker
          v-model="queryParams.endTime"
          type="datetime"
          placeholder="请选择结束时间"
          value-format="YYYY-MM-DD HH:mm:ss"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="审核状态" prop="status" style="width: 180px">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择审核状态"
          clearable
          @keyup.enter="handleQuery"
        >
          <el-option label="待审核" :value="0" />
          <el-option label="审核通过" :value="1" />
          <el-option label="不通过" :value="2" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['system:recordTime:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:recordTime:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:recordTime:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['system:recordTime:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="recordTimeList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="学生学号" align="center" prop="studentNumber" />
      <el-table-column label="学生姓名" align="center" prop="studentName" />
      <el-table-column label="方向名称" align="center" prop="directionId">
        <template #default="scope">
          <span>{{ getDirectionName(scope.row.directionId) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="开始时间" align="center" prop="startTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.startTime, "{y}-{m}-{d} {h}:{i}:{s}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束时间" align="center" prop="endTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.endTime, "{y}-{m}-{d} {h}:{i}:{s}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="总计时间(小时)" align="center" prop="sumTime">
        <template #default="scope">
          <span>{{ formatMinutesToHours(scope.row.sumTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="位置编号" align="center" prop="deskId" />
      <el-table-column label="审核人" align="center" prop="reviewPerson" />
      <el-table-column label="审核状态" align="center" prop="status">
        <template #default="scope">
          <span v-if="scope.row.status === 0">待审核</span>
          <span v-else-if="scope.row.status === 1">审核通过</span>
          <span v-else>不通过</span>
        </template>
      </el-table-column>
      <el-table-column label="学习成果" align="center" prop="result" width="120">
        <template #default="scope">
          <div v-if="scope.row.result">
            <div v-for="(link, index) in parseLinks(scope.row.result)" :key="index" style="margin-bottom: 5px;">
              <div v-if="isImageLink(link)">
                <el-image 
                  :src="link" 
                  :preview-src-list="[link]"
                  fit="cover"
                  style="width: 60px; height: 60px; border-radius: 4px;"
                  :preview-teleported="true"
                >
                  <template #error>
                    <div class="image-error">
                      <el-icon><picture-filled /></el-icon>
                    </div>
                  </template>
                </el-image>
              </div>
              <div v-else>
                <el-link :href="link" target="_blank" type="primary" style="font-size: 12px">
                  {{ getFileNameFromLink(link) }}
                </el-link>
              </div>
            </div>
          </div>
          <span v-else>-</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button
            link
            type="success"
            icon="Check"
            @click="handleReview(scope.row)"
            v-hasPermi="['system:recordTime:edit']"
            >审核</el-button
          >

          <el-button
            link
            type="primary"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:recordTime:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
      style="margin-top: 15px;"
    />

    <!-- 添加或修改记录学习时间对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="recordTimeRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="学生学号" prop="studentNumber">
          <el-input v-model="form.studentNumber" placeholder="请输入学生学号" disabled />
        </el-form-item>
        <el-form-item label="学生姓名" prop="studentName">
          <el-input v-model="form.studentName" placeholder="请输入学生姓名" disabled />
        </el-form-item>
        <el-form-item label="方向" prop="directionId">
          <el-select v-model="form.directionId" placeholder="请选择方向" disabled>
            <el-option
              v-for="item in directionOptions"
              :key="item.directionId"
              :label="item.directionName"
              :value="item.directionId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="学习内容">
          <el-input
            v-model="form.content"
            type="textarea"
            :autosize="{ minRows: 2 }"
            placeholder="请输入学习内容"
            disabled
          />
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker
            clearable
            v-model="form.startTime"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择开始时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker
            clearable
            v-model="form.endTime"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择结束时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="总计时间" prop="sumTime" disabled>
          <span>{{ formatMinutesToHours(calculatedSumTime) }}</span>
        </el-form-item>

        <el-form-item label="位置编号" prop="deskId">
          <el-input v-model="form.deskId" placeholder="请输入位置编号" />
        </el-form-item>
        <el-form-item label="审核人" prop="reviewPerson">
          <el-input v-model="form.reviewPerson" placeholder="请输入审核人" />
        </el-form-item>
        <el-form-item label="学习成果" prop="result">
          <div v-if="form.result">
            <div
              v-for="(link, index) in parseLinks(form.result)"
              :key="index"
              style="margin-bottom: 10px"
            >
              <div v-if="isImageLink(link)">
                <div style="margin-bottom: 5px; font-size: 14px; color: #606266;">材料{{ index + 1 }} (图片):</div>
                <el-image 
                  :src="link" 
                  :preview-src-list="[link]"
                  fit="cover"
                  style="width: 100px; height: 100px; border-radius: 4px; border: 1px solid #dcdfe6;"
                  :preview-teleported="true"
                >
                  <template #error>
                    <div class="image-error">
                      <el-icon><picture-filled /></el-icon>
                    </div>
                  </template>
                </el-image>
              </div>
              <div v-else>
                <el-link :href="link" target="_blank" type="primary">
                  <el-icon><document /></el-icon>
                  材料{{ index + 1 }}: {{ getFileNameFromLink(link) }}
                </el-link>
              </div>
            </div>
          </div>
          <el-input
            v-else
            v-model="form.result"
            placeholder="请输入学习成果材料链接，多个链接请用逗号分隔"
          />
        </el-form-item>

        <el-form-item label="审核状态" prop="status">
          <span>{{ getStatusText(form.status) }}</span>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button
            v-if="form.timeId && form.status !== 1"
            type="success"
            @click="handleApproveInForm"
            :loading="isApproving"
            >通过</el-button
          >
          <el-button
            v-if="form.timeId && form.status !== 2"
            type="danger"
            @click="handleRejectInForm"
            >不通过</el-button
          >
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 折线图组件
    <el-card shadow="never" style="margin: 60px 0;">
      <TimeChart :data="recordTimeList" />
    </el-card> -->

  </div>
</template>

<script setup name="RecordTime">
import { ref, reactive, toRefs, computed, getCurrentInstance } from 'vue';
import { PictureFilled, Document } from '@element-plus/icons-vue';
import {
  listRecordTime,
  getRecordTime,
  delRecordTime,
  addRecordTime,
  updateRecordTime,
} from "@/api/analyzemanagement/recordTime";
import { listDirection } from "@/api/directionmanagement/direction";
import { listLog, addLog, updateLog, delLog } from "@/api/analyzemanagement/log";
import useUserStore from "@/store/modules/user";
import TimeChart from './TimeChart.vue';

const { proxy } = getCurrentInstance();
const userStore = useUserStore();

const recordTimeList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const directionOptions = ref([]);
const isApproving = ref(false); // 用于控制“通过”按钮的加载状态

// 计算属性：根据开始时间和结束时间计算总时间（分钟）
const calculatedSumTime = computed(() => {
  if (form.value.startTime && form.value.endTime) {
    const start = new Date(form.value.startTime);
    const end = new Date(form.value.endTime);
    if (end > start) {
      const diffMs = end - start;
      const diffMins = Math.floor(diffMs / (1000 * 60));
      return diffMins;
    }
  }
  return 0;
});

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    studentNumber: null,
    studentName: null,
    directionId: null,
    startTime: null,
    endTime: null,
    sumTime: null,
    content: null,
    result: null,
    status: null,
    reviewPerson: null,
    deskId: null,
  },
  rules: {},
});

const { queryParams, form, rules } = toRefs(data);

/** 查询记录学习时间列表 */
function getList() {
  loading.value = true;
  listRecordTime(queryParams.value).then((response) => {
    recordTimeList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

/** 查询方向列表 */
function getDirectionList() {
  listDirection().then((response) => {
    directionOptions.value = response.rows;
  });
}

/** 根据方向ID获取方向名称 */
function getDirectionName(directionId) {
  if (!directionId) return "";
  const direction = directionOptions.value.find(
    (item) => item.directionId == directionId
  );
  return direction ? direction.directionName : "";
}

/** 解析链接数组 */
function parseLinks(links) {
  if (!links) return [];
  return links.split(",").filter((link) => link.trim() !== "");
}

/** 判断链接是否为图片 */
function isImageLink(link) {
  if (!link) return false;
  const imageExtensions = ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp', '.svg'];
  const lowerLink = link.toLowerCase();
  return imageExtensions.some(ext => lowerLink.includes(ext));
}

/** 从链接中获取文件名 */
function getFileNameFromLink(link) {
  if (!link) return '';
  try {
    // 尝试从URL中提取文件名
    const url = new URL(link);
    const pathname = url.pathname;
    const fileName = pathname.substring(pathname.lastIndexOf('/') + 1);
    return fileName || '下载文件';
  } catch (e) {
    // 如果URL解析失败，尝试直接从字符串中提取
    const lastSlashIndex = link.lastIndexOf('/');
    const fileName = lastSlashIndex !== -1 ? link.substring(lastSlashIndex + 1) : link;
    return fileName || '下载文件';
  }
}

/** 将分钟转换为小时和分钟 */
function formatMinutesToHours(minutes) {
  if (!minutes) return "0小时0分钟";
  const hours = Math.floor(minutes / 60);
  const remainingMinutes = minutes % 60;
  return `${hours}小时${remainingMinutes}分钟`;
}

/** 将审核状态转换为文字 */
function getStatusText(status) {
  if (status === 0) return "待审核";
  if (status === 1) return "审核通过";
  if (status === 2) return "不通过";
  return "";
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    timeId: null,
    studentNumber: null,
    studentName: null,
    directionId: null,
    startTime: null,
    endTime: null,
    sumTime: null,
    content: null,
    result: null,
    status: null,
    reviewPerson: null,
    createTime: null,
    deskId: null,
  };
  proxy.resetForm("recordTimeRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.timeId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  // 自动填充审核人为当前登录用户
  form.value.reviewPerson = userStore.name;
  open.value = true;
  title.value = "添加记录学习时间";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _timeId = row.timeId || ids.value;
  getRecordTime(_timeId).then((response) => {
    form.value = response.data;
    // 自动填充审核人为当前登录用户
    if (!form.value.reviewPerson) {
      form.value.reviewPerson = userStore.name;
    }
    open.value = true;
    title.value = "修改记录学习时间";
  });
}

/** 审核按钮操作 */
function handleReview(row) {
  reset();
  const _timeId = row.timeId || ids.value;
  getRecordTime(_timeId).then((response) => {
    form.value = response.data;
    // 自动填充审核人为当前登录用户
    form.value.reviewPerson = userStore.name;
    open.value = true;
    title.value = "审核记录学习时间";
  });
}




/** 表单中审核通过操作 */
function handleApproveInForm() {
  isApproving.value = true; // 开始加载
  proxy.$modal
    .confirm("是否确认审核通过该记录学习时间数据项？")
    .then(function () {
      // 将计算出的总时间赋值给表单的sumTime字段
      form.value.sumTime = calculatedSumTime.value;
      
      const updateData = {
        ...form.value,
        status: 1,
        reviewPerson: userStore.name,
      };
      return updateRecordTime(updateData);
    })
    .then(async () => {
      // 添加日志记录
      try {
        const logData = {
          logType: "1", // 4:学习时间
          studentNumber: form.value.studentNumber,
          studentName: form.value.studentName,
          content: `${form.value.studentName}的学习时间记录审核通过，总计时间：${formatMinutesToHours(form.value.sumTime)}`,
          score: form.value.sumTime||0, // 学习时间记录不涉及分数,为时间
          direction: form.value.directionId, // 直接使用当前数据中的方向信息
          recordId: form.value.timeId,
          createTime: form.value.createTime
        };

        // 根据logType和recordId查询是否存在该日志
        try {
          const logQuery = {
            logType: "1",
            recordId: form.value.timeId,
            studentNumber: form.value.studentNumber
          };
          const existingLogs = await listLog(logQuery);
          
          if (existingLogs.rows && existingLogs.rows.length > 0) {
            // 已存在日志，更新现有记录
            const existingLog = existingLogs.rows[0];
            const updateData = {
              ...existingLog,
              ...logData
            };
            await updateLog(updateData);
          } else {
            // 不存在日志，新增记录
            await addLog(logData);
          }
        } catch (queryError) {
          console.error("查询日志失败，尝试新增日志:", queryError);
          await addLog(logData);
        }
      } catch (logError) {
        console.error("添加日志失败:", logError);
        // 不阻止主流程，只记录错误
      }

      open.value = false;
      getList();
      proxy.$modal.msgSuccess("审核通过成功");
    })
    .catch(() => {})
    .finally(() => {
      isApproving.value = false; // 结束加载
    });
}

/** 表单中审核不通过操作 */
function handleRejectInForm() {
  proxy.$modal
    .confirm("是否确认审核不通过该记录学习时间数据项？")
    .then(function () {
      // 将计算出的总时间赋值给表单的sumTime字段
      form.value.sumTime = calculatedSumTime.value;
      
      const updateData = {
        ...form.value,
        status: 2,
        reviewPerson: userStore.name,
      };
      return updateRecordTime(updateData);
    })
    .then(async () => {
      // 添加日志记录
      try {
        

        // 根据logType和recordId查询是否存在该日志
        try {
          const logQuery = {
            logType: "1",
            recordId: form.value.timeId,
            studentNumber: form.value.studentNumber
          };
          const existingLogs = await listLog(logQuery);
          
          if (existingLogs.rows && existingLogs.rows.length > 0) {
            // 已存在日志，删除现有记录
            const existingLog = existingLogs.rows[0];
            await delLog(existingLog.id);
          }
          // 审核不通过不添加新日志，只删除之前的日志
        } catch (queryError) {
          console.error("查询日志失败:", queryError);
        }
      } catch (logError) {
        console.error("处理日志失败:", logError);
        // 不阻止主流程，只记录错误
      }

      open.value = false;
      getList();
      proxy.$modal.msgSuccess("审核不通过成功");
    })
    .catch(() => {});
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["recordTimeRef"].validate((valid) => {
    if (valid) {
      proxy.$modal.loading("正在提交中...");
      // 将计算出的总时间赋值给表单的sumTime字段
      form.value.sumTime = calculatedSumTime.value;
      
      if (form.value.timeId != null) {
        updateRecordTime(form.value).then((response) => {
          proxy.$modal.closeLoading();
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        }).catch(() => { proxy.$modal.closeLoading(); });
      } else {
        addRecordTime(form.value).then((response) => {
          proxy.$modal.closeLoading();
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        }).catch(() => { proxy.$modal.closeLoading(); });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _timeIds = row.timeId || ids.value;
  proxy.$modal
    .confirm('是否确认删除记录学习时间编号为"' + _timeIds + '"的数据项？')
    .then(function () {
      return delRecordTime(_timeIds);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "system/recordTime/export",
    {
      ...queryParams.value,
    },
    `recordTime_${new Date().getTime()}.xlsx`
  );
}

getList();
getDirectionList();
</script>

<style scoped>
.image-error {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background-color: #f5f7fa;
  color: #909399;
  font-size: 20px;
}
</style>
